<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="为什么要测量​    我们在xml里设置布局时，必须要设定它的宽和高，不设置的话就会报错。 这是因为我们必须要告诉系统我们的View/ViewGroup需要多大的区域去绘制它。当我们给它设置好宽高后，系统需要测量一下才能知道它的尺寸，从而确定需要多大的区域去绘制它。">
<meta property="og:type" content="article">
<meta property="og:title" content="Android View的测量">
<meta property="og:url" content="https://www.yanhaoblog.com/2017/01/21/Android-View的测量/index.html">
<meta property="og:site_name" content="闫浩的博客">
<meta property="og:description" content="为什么要测量​    我们在xml里设置布局时，必须要设定它的宽和高，不设置的话就会报错。 这是因为我们必须要告诉系统我们的View/ViewGroup需要多大的区域去绘制它。当我们给它设置好宽高后，系统需要测量一下才能知道它的尺寸，从而确定需要多大的区域去绘制它。">
<meta property="og:updated_time" content="2017-01-21T05:22:03.836Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android View的测量">
<meta name="twitter:description" content="为什么要测量​    我们在xml里设置布局时，必须要设定它的宽和高，不设置的话就会报错。 这是因为我们必须要告诉系统我们的View/ViewGroup需要多大的区域去绘制它。当我们给它设置好宽高后，系统需要测量一下才能知道它的尺寸，从而确定需要多大的区域去绘制它。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.yanhaoblog.com/2017/01/21/Android-View的测量/"/>





  <title> Android View的测量 | 闫浩的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">闫浩的博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
    
      <p class="site-subtitle">Sometimes you got to run before you can walk</p>
    
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="https://www.yanhaoblog.com/2017/01/21/Android-View的测量/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="闫浩">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/images/demo.png">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="闫浩的博客">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="闫浩的博客" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android View的测量
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-01-21T13:04:54+08:00">
                2017-01-21
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/01/21/Android-View的测量/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2017/01/21/Android-View的测量/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="为什么要测量"><a href="#为什么要测量" class="headerlink" title="为什么要测量"></a>为什么要测量</h3><p>​    我们在xml里设置布局时，必须要设定它的宽和高，不设置的话就会报错。 这是因为我们必须要告诉系统我们的View/ViewGroup需要多大的区域去绘制它。当我们给它设置好宽高后，系统需要测量一下才能知道它的尺寸，从而确定需要多大的区域去绘制它。<br><a id="more"></a><br>​    在View类里，使用了<code>measure(int widthMeasureSpec, int heightMeasureSpec)</code>测量一个View有多大，具体的测量是在<code>onMeasure(int widthMeasureSpec, int heightMeasureSpec)</code>,但是 <code>measure(int widthMeasureSpec, int heightMeasureSpec)</code>是final的，我们无法重写，我们只能去重写<code>onMeasure(int widthMeasureSpec, int heightMeasureSpec)</code>。 </p>
<p>​    在测量时会用到一个类 <code>MeasureSpec</code>,它会一直贯穿始终；它是一个非常重要的类，我们首先了解一下这个类。</p>
<h4 id="MeasureSpec"><a href="#MeasureSpec" class="headerlink" title="MeasureSpec"></a>MeasureSpec</h4><p>这个类名的字面翻译为测量细则或者测量规格；对于该类官方注释给出的介绍如下：</p>
<blockquote>
<p>MeasureSpec 封装了父布局对子View的布局要求，这个具体的要求父布局会传递给子View。每个MeasureSpec可以表示宽或者高。MeasureSpec由尺寸(size)和模式(mode)组成。</p>
</blockquote>
<p>MeasureSpec 使用的是 一个 32 位的int 数据实现。它将size和mode打包成了一份int型数值；其中高两位表示测量的模式，低30位表示该测量模式下的大小。它使用了各种位运算来计算这些值；如果有兴趣可以去看一下MeasureSpec的源码。那么我们怎么获取到mode 和 size 呢？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//获取宽的测量模式</span></div><div class="line"><span class="keyword">int</span> widthMode = MeasureSpec.getMode(widthMeasureSpec);</div><div class="line"><span class="comment">//获取高的测量模式</span></div><div class="line"><span class="keyword">int</span> heightMode = MeasureSpec.getMode(heightMeasureSpec);</div><div class="line"><span class="comment">//获取宽测量出的大小</span></div><div class="line"><span class="keyword">int</span> widthSize = MeasureSpec.getSize(widthMeasureSpec);</div><div class="line"><span class="comment">//获取高测量出的大小</span></div><div class="line"><span class="keyword">int</span> heightSize = MeasureSpec.getSize(heightMeasureSpec);</div></pre></td></tr></table></figure>
<p>​    当然如果你获取到了测量规格和大小之后也可以自己生成一个新的测量规格：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">int</span> newMeasureSpec=MeasureSpec.makeMeasureSpec(size, mode);</div></pre></td></tr></table></figure>
<p>上面提到的测量规格一共分为三种：</p>
<ol>
<li><strong>UNSPECIFIED</strong>，不限定。子View想要多大，父布局不会对它有任何限制，当然它不会超过父View的尺寸它的值为 0 。这个模式我们一般不会用到。我们遇到时最好给它一个确切的值。</li>
<li><strong>EXACTLY</strong>，精确的。它的父布局会决定它的大小。不管它想要多大，它都会被限制在指定的大小范围内。它的父布局会检查它的精确尺寸。一般我们指定了View的具体尺寸或者<code>match_parent</code>时才会用到它。如果子View的宽/高设置的是 <code>match_parent</code>，那么这个子View的尺寸就是确定的，父View的size就是它的size。</li>
<li><strong>AT_MOST</strong>，至多。它的父布局检测不到它的精确的尺寸， 那父布局会指定这个子View可以获取到额定的尺寸，这里的额定大小一般指恰好能包裹它的内容。一般我们在给View设置<code>wrap_content</code>时使用。如果子View的宽/高设置的<code>wrap_content</code>，那么说明它的尺寸是由它的内容决定的；但是它的尺寸最多跟父View的尺寸一致，无法超出父View。这样我们是无法得到它的具体尺寸的。只有等父View测量完成后才会的到子View的确切尺寸（父View会调用child.measure(int childWidthMeasureSpec,int childHeightMeasureSpec)方法去测量子View的尺寸）。比如我们的TextView，它的父View会去先测量一下它的文字的内容的尺寸才会给它设置尺寸；它的尺寸是由父View 指定的，它不会超过父View的尺寸。如果它的父View只有50px，而TextView的内容则占了100px,那么多出来的文字则会被截取掉不会再显示。</li>
</ol>
<p>上面提到的 widthMeasureSpec 和 heightMeasureSpec 都是父类传递过来的，我们只需要在测量时通过它们获取size和mode  就OK了；这与细节大家不用多关心，如果感兴趣可以去看一下ViewGroup的measureChildren和 measureChild方法。</p>
<h3 id="View-的测量"><a href="#View-的测量" class="headerlink" title="View 的测量"></a>View 的测量</h3><p> 说完 MeasureSpec 我们回到View的 onMeasure(int widthMeasureSpec, int heightMeasureSpec) 。它的代码很简单：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onMeasure</span><span class="params">(<span class="keyword">int</span> widthMeasureSpec, <span class="keyword">int</span> heightMeasureSpec)</span> </span>&#123;</div><div class="line">    setMeasuredDimension(</div><div class="line">      getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),</div><div class="line">      getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)</div><div class="line">    );</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>其中的 <code>setMeasuredDimension(int measuredWidth, int measuredHeight)</code>方法是用来保存测量的尺寸，如果我们需要重写onMeasure，那么一定要在这里调用这个方法；否者会抛出异常。它的两个参数就是测量出来的宽和高，当然这里我们可以在代码里写死，比如setMeasuredDimension(50，50)，当然这是不提倡的。</p>
<p>其中的 <code>getDefaultSize(int size, int measureSpec)</code>会根据MeasureSpec去计算默认的尺寸。它的代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//这里的size为建议的最小宽/高</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">getDefaultSize</span><span class="params">(<span class="keyword">int</span> size, <span class="keyword">int</span> measureSpec)</span> </span>&#123;</div><div class="line">    <span class="keyword">int</span> result = size;</div><div class="line">	<span class="comment">//获取测量的模式</span></div><div class="line">    <span class="keyword">int</span> specMode = MeasureSpec.getMode(measureSpec);</div><div class="line">    <span class="comment">//获取测量的尺寸</span></div><div class="line">    <span class="keyword">int</span> specSize = MeasureSpec.getSize(measureSpec);</div><div class="line">    <span class="keyword">switch</span> (specMode) &#123;</div><div class="line">    <span class="keyword">case</span> MeasureSpec.UNSPECIFIED:<span class="comment">//如果在UNSPECIFIED模式下，返回最最小宽/高</span></div><div class="line">        result = size;</div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    <span class="keyword">case</span> MeasureSpec.AT_MOST:</div><div class="line">    <span class="keyword">case</span> MeasureSpec.EXACTLY:<span class="comment">//AT_MOST、EXACTLY模式返回测量后的宽/高</span></div><div class="line">        result = specSize;</div><div class="line">        <span class="keyword">break</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> result;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>根据上面onMeasure方法的代码，可以知道getDefaultSize中传入的size是建议的最小宽/高；如果在UNSPECIFIED模式下，返回最最小宽/高，其它的模式就是返回测量后的宽/高。这里的最小宽/高 ，指的是我们在XML 布局中设置的 <code>android:minHeight/android:minWidth</code>,或者是View背景图的宽/高。当然我们也可重写getSuggestedMinimumWidth()/getSuggestedMinimumHeight()方法指定最小宽/高。</p>
<p>​    如果我们需要重写onMeasure 方法，那么上面的代码就是我们可以参考的模板代码。我们可以通过三种模式去分别设定不同的尺寸。</p>
<h3 id="ViewGroup的测量"><a href="#ViewGroup的测量" class="headerlink" title="ViewGroup的测量"></a>ViewGroup的测量</h3><p>我们上面提到 <code>measure(int widthMeasureSpec, int heightMeasureSpec)</code>方法就是在ViewGroup里调用的。当ViewGroup测量子View的尺寸是就会调用 <code>child.measure(childWidthMeasureSpec, childHeightMeasureSpec)</code>; 通过ViewGroup的源码一共找到两处调用这个方法的地方；一个是 <code>measureChild()</code>一个是<code>measureChildWithMargins()</code>这两个方法代码类似，只是<code>measureChildWithMargins()</code>方法测量的时候会将 我们设置的margin 值计算在内:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 测量一个子View，它测量时会将padding 计算在内</div><div class="line"> * <span class="doctag">@param</span> child 测量的View</div><div class="line"> * <span class="doctag">@param</span> parentWidthMeasureSpec 父类传递给该View的宽的测量规格的要求</div><div class="line"> * <span class="doctag">@param</span> parentHeightMeasureSpec 父类传递给该View的高的测量规格的要求</div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">measureChild</span><span class="params">(View child, <span class="keyword">int</span> parentWidthMeasureSpec,</span></span></div><div class="line">        <span class="keyword">int</span> parentHeightMeasureSpec) &#123;</div><div class="line">    <span class="keyword">final</span> LayoutParams lp = child.getLayoutParams();</div><div class="line"></div><div class="line">    <span class="keyword">final</span> <span class="keyword">int</span> childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,</div><div class="line">            mPaddingLeft + mPaddingRight, lp.width);</div><div class="line">    <span class="keyword">final</span> <span class="keyword">int</span> childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,</div><div class="line">            mPaddingTop + mPaddingBottom, lp.height);</div><div class="line"></div><div class="line">    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * 测量一个子View，它测量时不经会将padding计算在内，也会将margin计算在内</div><div class="line"> *</div><div class="line"> * <span class="doctag">@param</span> child 测量的子View</div><div class="line"> * <span class="doctag">@param</span> parentWidthMeasureSpec 父类传递给该View的宽的测量规格的要求</div><div class="line"> * <span class="doctag">@param</span> widthUsed 父View已使用的在横向上的额外空间，也可能是其他的子View使用横向上的额外空间</div><div class="line"> * <span class="doctag">@param</span> parentHeightMeasureSpec 父类传递给该View的高的测量规格的要求</div><div class="line"> * <span class="doctag">@param</span> heightUsed 父View已使用的在竖向上的额外空间，也可能是其他的子View使用的竖向上的额外空间</div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">measureChildWithMargins</span><span class="params">(View child,</span></span></div><div class="line">        <span class="keyword">int</span> parentWidthMeasureSpec, <span class="keyword">int</span> widthUsed,</div><div class="line">        <span class="keyword">int</span> parentHeightMeasureSpec, <span class="keyword">int</span> heightUsed) &#123;</div><div class="line">    <span class="comment">//包含子View margin 数据的 类</span></div><div class="line">    <span class="keyword">final</span> MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();</div><div class="line"></div><div class="line">    <span class="keyword">final</span> <span class="keyword">int</span> childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,</div><div class="line">            mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin</div><div class="line">                    + widthUsed, lp.width);</div><div class="line">    <span class="keyword">final</span> <span class="keyword">int</span> childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,</div><div class="line">            mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin</div><div class="line">                    + heightUsed, lp.height);</div><div class="line"></div><div class="line">    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这个两个方法会在不同的布局中使用，在 <code>FrameLayout</code>，<code>LinearLayout</code>等布局里就是用了measureChildWithMargin。它们在使用时会遍历所有的子View，只要不是gone的都会去测量一遍。它会先把MeasureSpec传递给子View, 然后根据子View的 LayoutParams 再计算它的最最大宽度和最大高度等需要的数值，如果还有子View它会重复走这个流程。具体代码可以参看FrameLayout的onMeasure方法。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/01/21/Android-View的绘制/" rel="next" title="Android View的绘制">
                <i class="fa fa-chevron-left"></i> Android View的绘制
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/01/21/Android-View的布局过程/" rel="prev" title="Android View的布局过程">
                Android View的布局过程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2017/01/21/Android-View的测量/"
           data-title="Android View的测量" data-url="https://www.yanhaoblog.com/2017/01/21/Android-View的测量/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/demo.png"
               alt="闫浩" />
          <p class="site-author-name" itemprop="name">闫浩</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#为什么要测量"><span class="nav-number">1.</span> <span class="nav-text">为什么要测量</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#MeasureSpec"><span class="nav-number">1.1.</span> <span class="nav-text">MeasureSpec</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#View-的测量"><span class="nav-number">2.</span> <span class="nav-text">View 的测量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ViewGroup的测量"><span class="nav-number">3.</span> <span class="nav-text">ViewGroup的测量</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">闫浩</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>


<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

<div class="powered-by">
Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a>
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>



        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"yanhaods"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  












  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
